#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>

#include <sml/graphics.h>

#include "kexec.h"

void print(const char* msg)
{
	static char buffer[16384];
	static display*  disp = NULL;
	static gfx_font* font = NULL;
	if (!disp)
	{
		disp = display_create(320, 240, 320,
			(DISPLAY_FORMAT_RGB565 | DISPLAY_BUFFER_STATIC),
			NULL, NULL);
		if (!disp)
			return;
		gfx_init(disp);
		font = gfx_font_load("font.tga", COLOR_BLACK);
		buffer[0] = '\0';
	}

	strcat(buffer, msg);
	gfx_font_print(0, 0, font, buffer);
	display_flip(disp);
}

void vassert(bool assertion, const char* msg)
{
	if (assertion)
		return;
	print(msg);
	while(true);
}

int main(int argc, char** argv) {
	(void) argc; /* not used */
	(void) argv; /* not used */

	print("Loading vmlinuz.bin...\n");
	FILE* fp = fopen("vmlinuz.bin", "rb");
	vassert(fp, "Failed to open kernel file.\n");
	vassert(fseek(fp, 0, SEEK_END) == 0, "Failed to seek to end of file.\n");
	long size = ftell(fp);
	vassert(size >= 0, "Failed to get length of file.\n");
	vassert(fseek(fp, 0, SEEK_SET) == 0, "Failed to seek to beginning of file.\n");
	void* kernel = malloc(size + 3);
	vassert(kernel, "Failed to allocate memory for kernel.\n");
	vassert(fread(kernel, size, 1, fp) == 1, "Failed to read kernel file.\n");
	fclose(fp);

	print("Running kexec...\n");
	kexec((void*)0x80600000, kernel, size,
		0, NULL, NULL, NULL);

	vassert(false, "Failed to  load kernel.\n");
	return EXIT_SUCCESS; // Never reached.
}
